﻿using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Core.Validation
{
    public static class DataAnnotationsValidationRunner
    {
        /// <summary>
        /// Gets the errors.
        /// </summary>
        /// <remarks>
        /// Warning: For some reason, DataTypeAttribute.IsValid() always returns "true", regardless of whether
        /// it is actually valid. Need to improve this test runner to fix that.
        /// </remarks>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public static IEnumerable<ValidationError> GetErrors(object instance)
        {
            return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ValidationError(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
        }
    }
}
